package com.zs.propertymanage.controller;

import com.zs.propertymanage.dataObj.R;
import com.zs.propertymanage.dataObj.entity.House;
import com.zs.propertymanage.dataObj.entity.PatrolTask;
import com.zs.propertymanage.dataObj.entity.WorkOrder;
import com.zs.propertymanage.mapper.*;
import com.zs.propertymanage.service.impl.OrgService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.*;

@RestController
@RequestMapping("stat")
public class StatisticsController {

    @Autowired
    private OrgService orgService;
    @Autowired
    private HouseMapper houseMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private TenantMapper tenantMapper;
    @Autowired
    private WorkOrderMapper workOrderMapper;
    @Autowired
    private PatrolMapper patrolMapper;

    // 查询总房屋数量、员工数量、租户数量
    @GetMapping("/total")
    public R getTotal() {
        HashMap<String, Integer> map = new HashMap<>();
        map.put("houseTotal", houseMapper.getTotal());
        map.put("employeeTotal", employeeMapper.getTotal());
        map.put("tenantTotal", tenantMapper.getTotal());
        map.put("workorderTotal", workOrderMapper.getTotal());
        map.put("taskTotal", patrolMapper.getTotal());

        return R.ok("查询总计数量成功", map);
    }

    // 房屋数据统计
    @GetMapping("/house/{orgId}")
    public R getHouseStat(@PathVariable Integer orgId) {
        // 根据所给orgId获取所有子id
        List<Integer> childrenIdList = orgService.getChildrenIdList(orgId);
        // 获取这些id下的所有house
        List<House> houseList = houseMapper.getHouseByOrgIdList(null, null, null, childrenIdList, false);
        // 统计这些房屋的分类数量和状态数量
        LinkedHashMap<String, Integer> typeMap = new LinkedHashMap<>();
        LinkedHashMap<String, Integer> statusMap = new LinkedHashMap<>();
        for (House house : houseList) {
            String typeName = house.getTypeName();
            String statusName = house.getStatusName();
            // 分类数量
            if (typeMap.containsKey(typeName))
                typeMap.put(typeName, typeMap.get(typeName) + 1);
            else
                typeMap.put(typeName, 1);
            // 状态数量
            if (statusMap.containsKey(statusName))
                statusMap.put(statusName, statusMap.get(statusName) + 1);
            else
                statusMap.put(statusName, 1);
        }
        // 将map装换成具有对应关系的数组
        Collection<String> typeMapKeys = typeMap.keySet();
        Collection<Integer> typeMapValues = typeMap.values();
        Collection<String> statusMapKeys = statusMap.keySet();
        Collection<Integer> statusMapValues = statusMap.values();

        String[] typeMapKeysArray = new String[typeMapKeys.size()];
        typeMapKeys.toArray(typeMapKeysArray);
        Integer[] typeMapValuesArray = new Integer[typeMapValues.size()];
        typeMapValues.toArray(typeMapValuesArray);
        String[] statusMapKeysArray = new String[statusMapKeys.size()];
        statusMapKeys.toArray(statusMapKeysArray);
        Integer[] statusMapValuesArray = new Integer[statusMapValues.size()];
        statusMapValues.toArray(statusMapValuesArray);
        // 封装结果
        HashMap<String, Object> houseStat = new HashMap<>();
        houseStat.put("typeName", typeMapKeysArray);
        houseStat.put("typeValue", typeMapValuesArray);
        houseStat.put("statusName", statusMapKeysArray);
        houseStat.put("statusValue", statusMapValuesArray);
        houseStat.put("houseTotal", houseList.size());

        return R.ok("查询房屋统计数据成功", houseStat);
    }

    // 工单数据统计
    @PostMapping("/workorder")
    public R getWorkOrderStat(@RequestBody LocalDateTime[] dateRange) {
        // 获取指定时间段中的所有工单
        List<WorkOrder> workOrderList = workOrderMapper.getWithDateTimeRange(dateRange[0].plusHours(8), dateRange[1].plusHours(8));

        // 遍历集合进行数据统计
        LinkedHashMap<String, Integer> categoryMap = new LinkedHashMap<>();
        LinkedHashMap<String, Integer> statusMap = new LinkedHashMap<>();
        statusMap.put("unreceived", 0);
        statusMap.put("processing", 0);
        statusMap.put("completed", 0);
        statusMap.put("closed", 0);
        for (WorkOrder workOrder : workOrderList) {
            String categoryName = workOrder.getCategoryName();
            Integer completeStatus = workOrder.getCompleteStatus(); // 1-待接收 2-处理中 3-已完成
            Integer closeStatus = workOrder.getCloseStatus();   // 1-已关闭 0-未关闭
            // 分类数量
            if (categoryMap.containsKey(categoryName))
                categoryMap.put(categoryName, categoryMap.get(categoryName) + 1);
            else
                categoryMap.put(categoryName, 1);
            // 状态数量
            switch (completeStatus) {
                case 1 -> statusMap.put("unreceived", statusMap.get("unreceived") + 1);
                case 2 -> statusMap.put("processing", statusMap.get("processing") + 1);
                case 3 -> statusMap.put("completed", statusMap.get("completed") + 1);
            }
            // 关闭数量（放在状态数量一起）
            if (closeStatus == 1)
                statusMap.put("closed", statusMap.get("closed") + 1);
        }

        // 将statusMap转换成具有对应关系的数组(statusValue)
        Collection<Integer> statusMapValues = statusMap.values();
        Integer[] statusMapValuesArray = new Integer[statusMapValues.size()];
        statusMapValues.toArray(statusMapValuesArray);

        // 将categoryMap转换成对象集合
        List<HashMap<String, Object>> categoryResultList = new ArrayList<>();
        // 获取categoryMap的entrySet
        Collection<Map.Entry<String, Integer>> categoryMapEntries = categoryMap.entrySet();
        for (Map.Entry<String, Integer> entry : categoryMapEntries) {
            HashMap<String, Object> entryMap = new HashMap<>();
            entryMap.put("name", entry.getKey());
            entryMap.put("value", entry.getValue());
            categoryResultList.add(entryMap);
        }

        // 封装结果
        HashMap<String, Object> workOrderStat = new HashMap<>();
        workOrderStat.put("statusValue", statusMapValuesArray);
        workOrderStat.put("workorderTotal", workOrderList.size());
        workOrderStat.put("categoryStat", categoryResultList);

        return R.ok("查询工单数据成功", workOrderStat);
    }

    // 巡查任务数据统计
    @PostMapping("/task")
    public R getTaskStat(@RequestBody LocalDateTime[] dateRange) {
        // 获取指定时间段中的所有工单
        List<PatrolTask> taskList = patrolMapper.getWithDateTimeRange(dateRange[0].plusHours(8), dateRange[1].plusHours(8));

        // 遍历集合进行数据统计
        LinkedHashMap<String, Integer> planMap = new LinkedHashMap<>();
        LinkedHashMap<String, Integer> statusMap = new LinkedHashMap<>();
        statusMap.put("uncompleted", 0);
        statusMap.put("completed", 0);
        statusMap.put("closed", 0);
        for (PatrolTask task : taskList) {
            String planName = task.getPlanName();
            Integer completeStatus = task.getCompleteStatus(); // 1-待接收 2-处理中 3-已完成
            Integer closeStatus = task.getCloseStatus();   // 1-已关闭 0-未关闭
            // 分类数量
            if (planMap.containsKey(planName))
                planMap.put(planName, planMap.get(planName) + 1);
            else
                planMap.put(planName, 1);
            // 状态数量
            switch (completeStatus) {
                case 0 -> statusMap.put("uncompleted", statusMap.get("uncompleted") + 1);
                case 1 -> statusMap.put("completed", statusMap.get("completed") + 1);
            }
            // 关闭数量（放在状态数量一起）
            if (closeStatus == 1)
                statusMap.put("closed", statusMap.get("closed") + 1);
        }

        // 将statusMap转换成具有对应关系的数组(statusValue)
        Collection<Integer> statusMapValues = statusMap.values();
        Integer[] statusMapValuesArray = new Integer[statusMapValues.size()];
        statusMapValues.toArray(statusMapValuesArray);

        // 将planMap转换成对象集合
        List<HashMap<String, Object>> planResultList = new ArrayList<>();
        // 获取planMap的entrySet
        Collection<Map.Entry<String, Integer>> planMapEntries = planMap.entrySet();
        for (Map.Entry<String, Integer> entry : planMapEntries) {
            HashMap<String, Object> entryMap = new HashMap<>();
            entryMap.put("name", entry.getKey());
            entryMap.put("value", entry.getValue());
            planResultList.add(entryMap);
        }

        // 封装结果
        HashMap<String, Object> taskStat = new HashMap<>();
        taskStat.put("statusValue", statusMapValuesArray);
        taskStat.put("taskTotal", taskList.size());
        taskStat.put("planStat", planResultList);

        return R.ok("未完成 task", taskStat);
    }

}
